package com.miyu.system.utils.webService;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.nio.charset.Charset;

public class SoapUtil {



    public static void main(String[] args) throws Exception {
        /*webservicve接口地址*/
        //String postUrl="http://localhost:8888//services/user?wsdl";
        String postUrl="http://localhost:18767/webService/testWebService/sendMsg?wsdl";
        /*//"http://tempuri.org/execute";*/
        String soapAction="";
        /*//命名空间*/
        String namespace="http://webService.utils.system.miyu.com/";
        /*//参数个数*/
        int paramsNum=0;
        //参数组
        String[] params={};
        /*//访问接口*/
        String result=SoapUtil.SplicingMessage(namespace, postUrl, soapAction, "sendMsg", paramsNum, params);
     //   System.out.println("返回的数据为："+result);



        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        root.addElement("serverName").addText("getFinancialDebit");
        root.addElement("format").addText("format");
        root.addElement("callOperator").addText("callOperator");
        root.addElement("certificate").addText("certificate");

        document.asXML();

        Document document1 = DocumentHelper.createDocument();
        Element root1 = document1.addElement("root");
        root1.addElement("serverName").addText("getFinancialDebit");
        root1.addElement("format").addText("format");
        root1.addElement("callOperator").addText("callOperator");
        root1.addElement("certificate").addText("certificate");

        document1.asXML();

//        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//        Client client = dcf.createClient("http://localhost:18767/webService/testWebService?wsdl");
//        Object[] objects = new Object[0];

//        objects = client.invoke("sendMsg",document.asXML(),document1.asXML());




    }



    /**
     * 访问webservice接口
     * @param namespace 命名空间
     * @param postUrl webservice接口地址
     * @param soapAction soapAction地址
     * @param method 方法名
     * @param paramsNum 参数个数
     * @param params 参数组
     * @return  返回值
     */
    public static String SplicingMessage(String namespace,String postUrl,String soapAction,String method,int paramsNum,String[] params){
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        root.addElement("serverName").addText("getFinancialDebit");
        root.addElement("format").addText("format");
        root.addElement("callOperator").addText("callOperator");
        root.addElement("certificate").addText("certificate");
        document.asXML();
        Document document1 = DocumentHelper.createDocument();
        Element root1 = document1.addElement("root");
        root1.addElement("serverName").addText("getFinancialDebit");
        root1.addElement("format").addText("format");
        root1.addElement("callOperator").addText("callOperator");
        root1.addElement("certificate").addText("certificate");
        document1.asXML();
        System.out.println("请求报文msgHeader0："+document.asXML());
        System.out.println("请求报文msgBody1："+document1.asXML());

        //自定义soap报文模板 注意：xmlns:web 与<soapenv:Body>后的属性（web）要一致
        StringBuffer sb=new StringBuffer("");
        sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"").append(namespace).append("\">");

        sb.append("<soapenv:Header/>");
        sb.append("<soapenv:Body><web:");
        sb.append(method);
        sb.append(">");
        sb.append("<msgHeader>"+"aaaaaaaaaaa"+"</msgHeader>");
        sb.append("<msgBody>"+"bbbbb"+"</msgBody>");
        for (int i = 0; i < paramsNum; i++) {
            sb.append("<arg0>"+params[i]+"</arg0>");
        }
        sb.append("</web:");
        sb.append(method);
        sb.append("></soapenv:Body></soapenv:Envelope>");
        String result=doPostSoap1_1(postUrl, sb.toString(), soapAction);

        return result;
    }


    /**
     * 使用SOAP1.1发送消息
     *
     * @param postUrl
     * @param soapXml
     * @param soapAction
     * @return
     */
    public static String doPostSoap1_1(String postUrl, String soapXml,
                                       String soapAction) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpPost.setConfig(requestConfig);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
        }
        return retStr;
    }
    }
